package nz.co.doherty.gwtpbreadcrumbs.client.ui.common;

import java.util.List;

import nz.co.doherty.gwtpbreadcrumbs.client.i8n.ClientConstants;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.philbeaudoin.gwtp.mvp.client.EventBus;
import com.philbeaudoin.gwtp.mvp.client.PresenterImpl;
import com.philbeaudoin.gwtp.mvp.client.proxy.PlaceManager;
import com.philbeaudoin.gwtp.mvp.client.proxy.Proxy;
import com.philbeaudoin.gwtp.mvp.client.proxy.ProxyFailureHandler;

public abstract class ListPresenter<Proxy_ extends Proxy<?>, Entity_, ListItemView_ extends ListItemView, ListItemPresenter_ extends ListItemPresenter<Entity_, ListItemView_>>
		extends PresenterImpl<ListView<Entity_>, Proxy_> implements
		ListView.Presenter {

	public static final Object TYPE_ListContent = new Object();

	protected final ProxyFailureHandler failureHandler;
	protected final PlaceManager placeManager;
	protected final ClientConstants constants;
	protected final ListItemFactory<Entity_, ListItemView_, ListItemPresenter_> itemFactory;

	public ListPresenter(
			EventBus eventBus,
			ListView<Entity_> view,
			ListItemFactory<Entity_, ListItemView_, ListItemPresenter_> itemFactory,
			Proxy_ proxy, ProxyFailureHandler failureHandler,
			PlaceManager placeManager, ClientConstants constants) {
		super(eventBus, view, proxy);
		this.placeManager = placeManager;
		this.constants = constants;
		this.failureHandler = failureHandler;
		this.itemFactory = itemFactory;
	}

	protected void setListData(List<Entity_> entityList) {
		setContent(TYPE_ListContent, null);
		for (final Entity_ entity : entityList) {
			itemFactory.create(entity, new AsyncCallback<ListItemPresenter_>() {

				@Override
				public void onSuccess(ListItemPresenter_ listItemPresenter) {
					addContent(TYPE_ListContent, listItemPresenter);
				}

				@Override
				public void onFailure(Throwable caught) {
					failureHandler.onFailedGetPresenter(caught);
				}
			});
		}
	}

}
